from django.shortcuts import render
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin
from . import models, ser
from rest_framework.decorators import action
from taotao.utils.response import APIResponse
from rest_framework.views import APIView
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.filters import OrderingFilter, SearchFilter
from .paginations import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.response import Response
from django.core.cache import cache
from taotao.utils.logger import log
from celery_task.update_goods import updateGoods


# Create your views here.


# 查看所有商品接口，单个商品接口
class GoodsListView(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    queryset = models.Goods.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = ser.GoodsSerializer
    pagination_class = PageNumberPagination

    # 过滤和排序
    filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]
    ordering_fields = ['id', 'price']
    search_fields = ['category']

    def list(self, request, *args, **kwargs):
        queryset = cache.get('goods_list')
        if not queryset:
            print('走数据库拿数据')
            queryset = self.get_queryset()
            cache.set('goods_list', queryset)
        response = super().list(request, *args, **kwargs)
        return Response(response.data)


# 商品分类推荐接口
class CategoryView(GenericViewSet):
    @action(methods=['GET'], detail=False)
    def get_list(self, request, *args, **kwargs):
        from django.conf import settings
        # print(request.query_params) #<QueryDict:x {'category': ['1']}>
        # 如果url是re_path('category/(?P<category>\d+)',views.CategoryView.as_view(actions={'get':'get_list'}))
        # 那么 print(kwargs) #{'category': '1'}
        category = request.query_params.get('category')
        id = request.query_params.get('id')
        # print(id)
        queryset = models.Goods.objects.filter(is_delete=False, is_show=True, category=category).order_by(
            'orders').exclude(id=id)
        serializer = ser.GoodsSerializer(queryset, many=True)
        for goods in serializer.data:
            goods['goods_img'] = settings.BASE_URL + goods['goods_img']
        return APIResponse(code=1, msg='成功', result=serializer.data)


# 用户上传商品接口
class UploadView(GenericViewSet, CreateModelMixin):
    authentication_classes = [JSONWebTokenAuthentication, ]
    permission_classes = [IsAuthenticated, ]

    @action(methods=['post'], detail=False)
    def pub(self, request, *args, **kwargs):
        serializer = ser.GoodsSerializer(data=request.data, context={"request": request})
        if serializer.is_valid():
            serializer.save()
            updateGoods.delay()  # 手动提交更新缓存任务
            return APIResponse(code=1, msg='上传成功')
        return APIResponse(code=0, msg=serializer.errors)


from celery_task.limit_task import can_pass_token_bucket


# 用户查看自己发布的商品接口
class PersonGoodsView(APIView):
    authentication_classes = [JSONWebTokenAuthentication, ]
    permission_classes = [IsAuthenticated, ]

    def get(self, request, *args, **kwargs):
        try:
            user = request.user
            is_true = can_pass_token_bucket()
            if is_true:
                queryset = models.Goods.objects.filter(is_delete=False, create_user=user)
                serializer = ser.GoodsSerializer(queryset, many=True)
                return APIResponse(code=1, msg='成功', result=serializer.data)
            return APIResponse(code=0, msg='接口访问令牌数不足')
        except Exception as e:
            print(e)
            return APIResponse(code=0, msg='访问异常')


# 个人用户商品修改,下架接口
class GoodsDetailView(APIView):
    authentication_classes = [JSONWebTokenAuthentication, ]
    permission_classes = [IsAuthenticated, ]

    def put(self, request, pk):
        user = request.user
        instance = models.Goods.objects.filter(is_delete=False, create_user=user, id=pk).first()
        if instance:
            serializer = ser.GoodsSerializer(instance=instance, data=request.data)
            if serializer.is_valid():
                serializer.save()
                updateGoods.delay()  # 手动提交更新缓存任务
                return APIResponse(code=1, msg='修改成功')
            return APIResponse(code=0, msg=serializer.errors)
        return APIResponse(code=0, msg='异常动作')

    def delete(self, request, pk):
        user = request.user
        instance = models.Goods.objects.filter(pk=pk, create_user=user, is_delete=False).first()
        print(instance, type(instance))  # 自行车1 <class 'goods.models.Goods'>
        if instance:
            instance.is_delete = True
            instance.save()
            updateGoods.delay()  # 手动提交更新缓存任务
            return APIResponse(code=1, msg='下架成功')
        return APIResponse(code=0, msg='该商品不存在')


# 商品名模糊搜索
class GoodsSearchView(GenericViewSet, ListModelMixin):
    queryset = models.Goods.objects.filter(is_delete=False, is_show=True)
    serializer_class = ser.GoodsSerializer
    pagination_class = PageNumberPagination

    filter_backends = [SearchFilter]
    search_fields = ['name']
